<template>
  <div>
    <common-head title="所有联系人"/>
    <div class="wrap">
      <van-address-list
      v-model="chosenAddressId"
      :list="contacts"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="choseContact"
    />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      chosenAddressId: -1
    }
  },
  created () {
    this.initchoseId()
  },
  methods: {
    choseContact (contact) {
      // 切换联系人
      this.$store.commit('order/set_order_contact', contact)
      this.$router.replace('/order')
    },
    initchoseId () {
      /*
      优先找默认联系人 有的 是默认联系人的id
      没有找第一个
      */
      // 查找有没有默认联系人
      if (!this.contacts.length) {
        return
      }
      const defaultContact = this.contacts.find(el => el.isDefault)
      if (defaultContact) {
        // 有默认联系人
        this.chosenAddressId = defaultContact.id
      } else {
        this.chosenAddressId = this.contacts[0].id
      }
    },
    onAdd () {
      this.$router.push('/contactAdd')
    },
    onEdit (contact, index) {
      // 跳转路由 传 id(index)
      this.$router.push({
        path: '/contactEdit',
        query: {
          index
        }
      })
    }
  },
  components: { CommonHead },
  computed: {
    ...mapState({
      contacts: state => state.contact.contacts
    })
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  padding-top: 46px;
}
</style>
